
import { useRouter } from 'vue-router'
import { getToken, removeToken } from './auth'
import axios, { type Method } from 'axios'

const router = useRouter()

const service = axios.create({
  baseURL: 'https://geek.itheima.net/',
  timeout: 20 * 1000,
})

export interface ServiceResponse<T> {
  code: number
  msg: string
  data: T
}
export const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  // requst <默认data类型，后端返回值类型，config请求配置类型>
  return service.request<ServiceResponse<T>>({
    url: url,
    method: method,
    // []插值表达式 动态设置 对象的键名称
    // 请求参数GET放在params，POST放在data
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 如果有token，自动添加到请求头
    if (getToken()) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    // 相应拦截器中减少了一层data，直接获取后端返回值类型
    return response
  },
  error => {

      if (error.response.status === 401) {
        // 清除token
        removeToken()
        // 跳转到登录页
        router.push('/login')
      }
    return Promise.reject(error)
  }
)

export default service
